import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './userStore'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'



export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    const cartList = ref([])
        //获取最新购物车列表
    const getCartList = async() => {
            const res = await findNewCartListAPI()
            cartList.value = res.result

        }
        // 登录状态下从服务器获取购物车列表
    const addCart = async(goods) => {
            const { skuId, count } = goods

            if (isLogin.value) {
                await insertCartAPI({ skuId, count })
                getCartList()
            } else {
                const item = cartList.value.find((item) => goods.skuId === item.skuId)
                if (item) {
                    item.count++
                } else {
                    cartList.value.push(goods)
                    console.log(goods);

                }
            }


        }
        // 未登录状态下从本地获取购物车列表
        //删除购物车商品
    const delCart = async(skuId) => {
        if (isLogin.value) {
            delCartAPI([skuId])
            getCartList()
        } else {
            const index = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(index, 1)
        }
    }

    //退出登录时清空购物车列表
    const clearCart = () => {
            cartList.value = []
        }
        //单选操作
    const singleCheck = (skuId, selected) => {
            const item = cartList.value.find((item) => skuId === item.skuId)
            item.selected = selected
        }
        // 计算属性
        // 总数量
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
        // 总价
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.price * c.count, 0))
        //已选择数量
    const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count, 0))
        // 已选择总价
    const selectedPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((a, c) => a + c.count * c.price, 0))
        // 全选操作

    const isAll = computed(() => cartList.value.every((item) => item.selected))
    const allCheck = (selected) => {
        cartList.value.forEach((item) => item.selected = selected)
    }
    return {
        cartList,
        allCount,
        allPrice,
        selectedCount,
        selectedPrice,
        isAll,
        clearCart,
        allCheck,
        singleCheck,
        addCart,
        delCart,
        getCartList
    }

}, {
    persist: true,
})